package service;

import java.util.List;

import com.jfinal.aop.Aop;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import model.RoleMenu;
import model.User;


public class MenuToRoleService extends BaseService {	

	static UserRoleService userRoleService = Aop.get(UserRoleService.class) ;
	
	public List<RoleMenu> getMenuRoleList() {
		List<RoleMenu> menuList = RoleMenu.dao.findAll();
		return menuList;
				
	}

	public Ret save( Long roleId, String menuIds , User loginUser ) {
		Db.delete("delete from t_role_menu where roleId = ?",roleId);
		if(StrKit.isBlank(menuIds)) {
			return ok();
		}
		List<Record> list = userRoleService.findUserToMenu(loginUser);
		String[] menuArr = menuIds.split(",");
		for(String menuId:menuArr) {
			if (!isAuthMenu(list, Long.valueOf(menuId) )) {
				throw new RuntimeException("超出最大权限配置");
			}
			RoleMenu roleMenu = new RoleMenu();
			roleMenu.set("roleId", roleId);
			roleMenu.set("menuId", menuId);
			roleMenu.save();
		}
		return Ret.ok();
	}
	
	public boolean isAuthMenu( List<Record> list , Long menuId) {
		for (Record menu : list) {
			if (menu.getLong("id").equals(menuId)) {
				return true ;
			}
		}
		return false ;
	}

	public List<Record> getMenuBYRordId(String roleId) {
		return Db.find("select * from t_role_menu where rolid=?",roleId);
	}

}
